import React, { useEffect, useRef, useState } from "react";
import { get } from "../../util/get";
import { Table, Tag, Space, Button, Modal, Form, Input, message, Select } from "antd";
import { EditOutlined, DeleteOutlined,ExclamationCircleOutlined} from "@ant-design/icons"
import { post } from "../../util/post";
import EditResourceModal from "../../components/EditResourceModal";
import PubSub from "pubsub-js";
import style from "./index.module.css"
const { Column } = Table;
const {confirm} = Modal;
const Resource = () => {
    const token = localStorage.getItem('TOKEN')
    const [data, setData] = useState([])
    const [total, setTotal] = useState(0)
    const [page, setPage] = useState(1)
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [editV,setEditV]=useState(false)
    const ref= useRef()
    const map = new Map([['GET','#4ab793'],['POST','#e28335'],['PUT','#187fde']])
    const getResourceList = async () => {
        const res = await get(`/user/permission/list?page=${page}&limit=7`, token) 
        const { code, msg, page: { list, totalCount } } = res.data;
        if (code === 0) {
            setData(list)
            setTotal(totalCount)
        }
        else message.error(msg)
    }
    useEffect(() => {
        getResourceList()
    }, [page,token])
    const handleCancel = () => {
        setIsModalVisible(false);
    };
    const onFinish = async (values) => {
        // console.log(values, 'post')
        const res = await post('/user/permission/save', values, token)
        const { code, msg } = res.data;
        if (code === 0) {
            message.success(msg)
            setData([...data,values])
            setIsModalVisible(false)
            ref.current.resetFields();
        } else message.error(msg)
    };
    const onFinishFailed = (errorInfo) => {
        message.error(errorInfo);
    };
    const renderForm = () => {
        return (
            <Form name="basic" labelCol={{ span: 6 }}
                wrapperCol={{ span: 16 }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
                ref={ref}
            >
                <Form.Item
                    label="请求方法"
                    name="method"
                    rules={[
                        {
                            required: true,
                            message: '此为必填项',
                        },
                    ]}
                >
                    <Select>
                        <Select.Option value="GET">GET</Select.Option>
                        <Select.Option value="POST">POST</Select.Option>
                        <Select.Option value="PUT">PUT</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item
                    label="接口uri"
                    name="uri"
                    rules={[
                        {
                            required: true,
                            message: '此为必填项',
                        },
                    ]}
                >
                    <Input></Input>
                </Form.Item>
                <Form.Item
                    label="描述"
                    name="description"
                    rules={[
                        {
                            required: true,
                            message: '此为必填项',
                        },
                    ]}
                >
                    <Input></Input>
                </Form.Item>
                <Form.Item
                    wrapperCol={{
                        offset: 8,
                        span: 16,
                    }}
                >
                    <Button type="primary" htmlType="submit">
                        提交
                    </Button>
                </Form.Item>
            </Form>
        )
    }
    const handleEdit = (data) => {
        PubSub.publish('editResource',data)
        setEditV(true)
    }
    const handleDelete = (item) => {
        confirm({
                title: '你确定要删除该条资源吗',
                icon: <ExclamationCircleOutlined />,
                onOk() {
                    post('/user/permission/delete',[item.id],token).then(res=>{
                        const{msg,code}=res.data
                        if(!code) {
                            message.success(msg);
                            getResourceList();
                        }
                        else message.error(msg);
                    })
                },
                onCancel() {
                },
        })
    }
    const addResource = () => {
        setIsModalVisible(true)
    }
    const handleEditCancel = ()=>{
        setEditV(false);
    }
    return (
        <>
            <Button type="primary" className={style.add} shape="round" onClick={addResource}  >
                新增资源
            </Button>
            <Modal title="新增资源" visible={isModalVisible} footer={null} onCancel={handleCancel}>
                {
                    renderForm()
                }
            </Modal>
            <EditResourceModal v={editV} setV={setEditV}></EditResourceModal>
            <Table dataSource={data}
            pagination={{
                total,
                defaultPageSize:7,
                onChange:(page)=>{
                  setPage(page)
                }
              }}
            >
                <Column title="请求方法" dataIndex={"method"} key={"method"} render={
                    (v)=><Tag color={map.get(v)}>{v}</Tag>
                } />
                <Column title="接口uri" dataIndex={"uri"} key={"uri"} />
                <Column title="描述" dataIndex={"description"} key={"description"} />
                <Column title="操作" dataIndex={"action"} key={"action"} render={(_,item) => {
                    return (
                        <Space>
                            <Button type="primary" onClick={() => handleEdit(item)} shape="circle" icon={<EditOutlined />} size={"large"} />
                            <Button type="primary" onClick={() => handleDelete(item)} danger shape="circle" icon={<DeleteOutlined />} size={"large"} />
                        </Space>
                    )
                }}>

                </Column>
            </Table>
        </>
    )
}
export default Resource;
